package com.guohao.http.util;

import cn.hutool.core.util.ObjectUtil;
import com.guohao.http.RequestInfo;
import com.sun.net.httpserver.HttpExchange;
import java.io.StringReader;
import java.util.StringTokenizer;

public class RequestParse {

  public static RequestInfo getRequestInfo(HttpExchange exchange) {
    RequestInfo requestInfo = new RequestInfo(exchange.getRequestURI().getPath(),
        exchange.getRequestBody(), exchange.getRequestHeaders(), exchange.getRequestMethod());
    String strQuery = exchange.getRequestURI().getQuery();
    if (ObjectUtil.isNotEmpty(strQuery)){
      StringTokenizer queryTokenizer = new StringTokenizer(strQuery, "&");
      while (queryTokenizer.hasMoreTokens()) {
        try (StringReader stringReader = new StringReader(queryTokenizer.nextToken());) {
          requestInfo.getQuery().load(stringReader);
        } catch (Exception e) {
          e.printStackTrace();
        }
      }
    }
    return requestInfo;
  }
}
